package spring.cloud.tasks.tasks_manager.schedule;

import spring.cloud.tasks.common.DateUtils;
import spring.cloud.tasks.common.curator.Curator;
import spring.cloud.tasks.common.nodepaths.TaskNodePaths;
import spring.cloud.tasks.tasks_manager.task_item_assign.TaskItemAssignUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 任务信息变化很小。执行器信息动态变化，所以执行器信息必须实时获取。
 */
public class TaskIdListContext {
    public TaskIdLists taskIdLists = new TaskIdLists();

    public static class TaskIdLists {
        public volatile Long tasksUpdateVersion;
        public volatile long lastUpdateVersion = System.currentTimeMillis();
        public List<String> taskIdList = new ArrayList<>();
        public List<String> enableTaskIdList = new ArrayList<>();
        public List<String> pauseTaskIdList = new ArrayList<>();
    }

    /**
     * 基于更新版本做优化
     */
    public boolean refresh(Curator curator) throws InterruptedException {
        try {
            String tasksUpdateVersionNodePath = TaskNodePaths.getTasksUpdateVersionNodePath();
            String data = curator.getData(tasksUpdateVersionNodePath);
            if (data == null) {
                getTaskIdLists(curator, Long.parseLong(data));//强制获取数据
                return true;
            }
            if (this.taskIdLists.tasksUpdateVersion == null) {
                getTaskIdLists(curator, Long.parseLong(data));
                return true;
            }
            if (this.taskIdLists.tasksUpdateVersion.longValue() != Long.parseLong(data)) {
                getTaskIdLists(curator, Long.parseLong(data));
                return true;
            }
            if (System.currentTimeMillis() - this.taskIdLists.lastUpdateVersion > DateUtils.MINUTE) {
                getTaskIdLists(curator, Long.parseLong(data));
                return true;
            } else {
                return true;
            }
        } catch (Throwable e) {
            return false;
        }
    }

    /**
     * 耗时1秒
     */
    private TaskIdLists getTaskIdLists(Curator curator, Long tasksUpdateVersion) throws Exception {
        List<String> taskIdList = TaskItemAssignUtils.getTaskIdList(curator);
        List<String> enableTaskIdList = TaskItemAssignUtils.getEnableTaskIdList(curator, taskIdList);
        List<String> pauseTaskIdList = TaskItemAssignUtils.getPauseTaskIdList(curator);
        //
        TaskIdLists taskIdLists = new TaskIdLists();
        taskIdLists.taskIdList = taskIdList;
        taskIdLists.enableTaskIdList = enableTaskIdList;
        taskIdLists.pauseTaskIdList = pauseTaskIdList;
        //
        taskIdLists.tasksUpdateVersion = tasksUpdateVersion;
        taskIdLists.lastUpdateVersion = System.currentTimeMillis();
        //
        this.taskIdLists = taskIdLists;
        return taskIdLists;
    }
}
